<template>
  <el-drawer v-model="visible" direction="btt" class="add-interval jzt-drawer">
    <template #title>
      <div class="title-box">
        <CustomTitle title="商品区间和定价系数设置" />(系数定义：1为保持现有成本价，不加价不减价，以此推算，成本价*系数=售价)
      </div>
    </template>
    <div class="content">
      <div>商品成本范围空间</div>
      <template v-if="!forms.length">
        <el-empty />
        <div class="add-button">
          <el-button type="primary" @click="add">添加区间</el-button>
        </div>
      </template>
      <el-form v-for="(item, index) in forms" :model="item" ref="itemRef" :rules="rules">
        <div class="form">
          <div class="form-item-range">
            <el-form-item label="成本价范围：" prop="startPrice">
              <el-input v-model="item.startPrice" @keyup.enter="inquire(item, index)" @blur="inquire(item, index)"></el-input>
            </el-form-item>
            <span>至</span>
            <el-form-item prop="endPrice">
              <el-input v-model="item.endPrice" @keyup.enter="inquire(item, index)" @blur="inquire(item, index)"></el-input>
            </el-form-item>
          </div>
          <div class="form-item">
            <el-form-item label="设置为：" prop="coefficientType">
              <el-select style="width: 130px" v-model="item.coefficientType">
                <el-option :value="1" label="正价系数"></el-option>
                <el-option :value="2" label="特价系数"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="pricingCoefficient" style="flex: 1">
              <el-input v-model="item.pricingCoefficient" @keyup.enter="inquire(item, index)" @blur="inquire(item, index)">
              </el-input>
            </el-form-item>
          </div>
          <el-form-item>
            平均毛利润：
            <span v-if="!isShow.includes(item.averageGrossMargin)">{{ item.averageGrossMargin }}%</span>
            <span v-else>--</span>
            <img v-if="Number(item.averageGrossMargin)" :src="Number(item.averageGrossMargin) > 0 ? up : down" alt="" />
          </el-form-item>
          <el-form-item>
            原有毛利润值：
            <span v-if="!isShow.includes(item.oldAverageGrossMargin)">{{ item.oldAverageGrossMargin }}%</span>
            <span v-else>--</span>
          </el-form-item>
          <el-form-item>
            <img src="@/assets/images/del.png" @click="forms.splice(index, 1)" alt="" />
          </el-form-item>
        </div>
      </el-form>
      <div class="add" v-if="forms.length" @click="add">
        <el-icon> <CirclePlusFilled /> </el-icon>继续添加区间
      </div>
    </div>
    <template #footer>
      <div class="footer-btn">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="save">保存为定价草稿</el-button>
      </div>
    </template>
  </el-drawer>
</template>
<script setup>
import { computed, ref } from "vue";
import up from "@/assets/images/up.png";
import down from "@/assets/images/down.png";
import CustomTitle from "@/components/CustomTitle/index.vue";
import { getOrdinaryGrossMargin } from "@/apis/pricing";

const props = defineProps({
  show: {
    type: Boolean,
    required: true,
    default: false
  },
  data: {
    type: Object,
    required: true,
    default: () => ({})
  }
});
const itemRef = ref(null);
const emit = defineEmits(["update:show", "comfirm"]);
const forms = ref([...JSON.parse(JSON.stringify(props.data?.normalPricing?.pricingList || []))]);
const visible = computed({
  set: val => {
    emit("update:show", val);
  },
  get: () => {
    return props.show;
  }
});
const isShow = [null, undefined];
const inquire = async (item, index) => {
  const redg = /^[0-9]+(\.[0-9]{1,2})?$/;
  const arr = [redg.test(item.startPrice), redg.test(item.endPrice), redg.test(item.pricingCoefficient)];
  if (arr.every(v => v)) {
    const res = await getOrdinaryGrossMargin({ ...item, categoryId: props.data.categoryId });
    item.averageGrossMargin = res.data.averageGrossMargin;
    item.oldAverageGrossMargin = res.data.oldAverageGrossMargin;
  }
};
const rules = {
  startPrice: [
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
    { required: true, message: "请输入", trigger: "blur" }
  ],
  endPrice: [
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的金额", trigger: "blur" },
    { required: true, message: "请输入", trigger: "blur" }
  ],
  pricingCoefficient: [
    { required: true, message: "请输入系数", trigger: "blur" },
    { pattern: /^[0-9]+(\.[0-9]{1,2})?$/, message: "请输入正确的系数", trigger: "blur" }
  ],
  coefficientType: [{ required: true, message: "请选择系数类型", trigger: "change" }]
};
const defaultItem = {};
const add = () => {
  forms.value.push({ ...defaultItem });
};
const save = async () => {
  if (forms.value.length) {
    let arr = [];
    itemRef.value.forEach(v => {
      arr.push(
        new Promise(resolve => {
          v.validate(valid => {
            resolve(valid);
          });
        })
      );
    });
    const result = await Promise.all(arr);
    if (result.every(v => v)) emit("comfirm", forms.value);
  } else {
    emit("comfirm", forms.value);
  }
};
</script>
<style scoped lang="scss">
$border: 1px solid #e2e8f0;
$topic: #007dff;

.el-divider--horizontal {
  margin: 0 !important;
}

.footer-btn {
  padding: 0 20px;
  height: 60px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: end;
}

.add-button {
  display: flex;
  justify-content: center;
}

.el-empty {
  padding-bottom: 10px;
}
.title-box {
  display: flex;
  align-items: center;
  gap: 4px;
}
.content {
  > div:first-child {
    margin-bottom: 20px;
  }

  .form {
    display: flex;
    align-content: center;
    gap: 20px;

    .form-item-range {
      flex: 1;
      display: flex;

      ::v-deep(.el-form-item) {
        &:first-child {
          width: calc(50% + 55px);
        }

        &:last-child {
          width: calc(50% - 55px);
        }
      }

      span {
        height: 32px;
        line-height: 32px;
        margin: 0 10px;
      }
    }

    .form-item {
      flex: 1;
      display: flex;

      ::v-deep(.el-select__wrapper) {
        border-right: $border;
      }

      ::v-deep(.el-input__wrapper) {
        flex: 1;
      }
    }

    img {
      width: 16px;
      height: 16px;
      cursor: pointer;
    }

    .red {
      color: red;
    }

    .green {
      color: rgb(43, 208, 40);
    }
  }

  .add {
    color: $topic;
    display: flex;
    height: 40px;
    gap: 10px;
    align-items: top;
    cursor: pointer;
    width: 120px;
  }
}
</style>
<style lang="scss">
$border: 1px solid #e2e8f0;

.add-interval {
  padding: 0 !important;
  left: 5vw !important;
  height: 90vh !important;
  width: 90vw !important;
  border-radius: 10px 10px 0 0 !important;

  .el-drawer__footer {
    box-shadow: 0px -3px 10px 0px rgba(143, 162, 185, 0.1);
    align-items: center;
    padding: 0 !important;
  }

  .el-drawer__header {
    margin-bottom: 0 !important;
    border-bottom: $border;
    padding-bottom: 20px !important;
  }
}
</style>
